<?php
/**
 * 后台优化处理Controller
 */
namespace Common\Controller;
use Common\Controller\AdminbaseController;
class WahahabaseController extends AdminbaseController {
    // model
	protected $deal_model, $att_model;
	// 重复验证字段
	public $check;
	
    function _initialize(){
        parent::_initialize();
        $this->consignee_model = D("Common/Consignee");
    }
    

    /**
     * 查询列表数据
     **/
    public function indexPage($where){
        $eq = array(
            "eq" => "=",
            "neq" => "!=",
            "gt" => ">",
            "egt" => ">=",
            "lt" => "<",
            "elt" => "<=",
            "like" => "LIKE"
        ); 
        // 当前登录人
        $adminId = session('ADMIN_ID');
        $adminGroup = getUserInfo($adminId);
        //权限设置 20171228
        $condition = "(
            (d.is_publish = 0 AND (d.add_user = $adminId OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department) AND ((SELECT role_id FROM hzzy_users WHERE id=$adminId) IN('1','2','3'))))
            OR
            (d.is_publish = 1   
                AND (
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u1 LEFT JOIN hzzy_department d1 ON u1.department_id = d1.id WHERE u1.id=$adminId)
                        <= 
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u2 LEFT JOIN hzzy_department d2 ON u2.department_id = d2.id WHERE u2.id=d.add_user)
                )
                AND  '$adminGroup[department_role]' in ('1','2','3')
                OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department)
            )
            OR
            ((SELECT role_id FROM hzzy_users WHERE id=$adminId) = 0 AND d.is_publish = 1)
        )";
        foreach($where as $key => $v){
            if(count($v) > 1){
                $d = $eq[$v[0]] == NULL ? '=' : $eq[$v[0]];
                if($d != 'LIKE'){
                    $condition .= " AND $key $d '".$v[1]."'";
                } else {
                    $condition .= " AND $key $d '%".$v[1]."%'";
                }
            } else {
                $condition .= " AND $key = '$v'";
            }
        }

        $count=$this->deal_model->alias("d")->where($condition)->count();
        $page = $this->page($count, 20);
        
        $results = $this->deal_model->alias("d")
            ->field('d.*,u.real_name')
            ->join(array(
                ' LEFT JOIN '.C('DB_PREFIX').'users u ON d.add_user = u.id',
            ))
            ->where($condition)
            ->order("d.add_time DESC")
            ->limit($page->firstRow, $page->listRows)
            ->select();
		//exit($this->deal_model->getLastSql());	
        $this->assign("page", $page->show('Admin'));
        $this->assign("results",$results);
        
        $this->display();
    }
    
    /**
     * 新增保存
     **/
    public function addPost($url){
        if(IS_POST){
			$this->dataCheck();
            $data = array_merge($_POST, $this->saveData());
            if ($this->deal_model->create()!==false) {
                $result = $this->deal_model->add($data);
                if ($result!==false) {
                    $this->success("添加成功！", $url);
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }
    public function addFilePost($url, $type){
        if(IS_POST){
            $this->dataCheck();
            $data = array_merge($_POST, $this->saveData());
            if ($this->deal_model->create()!==false) {
                $result = $this->deal_model->add($data);
                if ($result!==false) {
                    $this->saveFile($result, $type);
                    $this->success("添加成功！", $url);
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }
    
    /**
     * 修改查询
     **/
    public function editdisplay(){
        $id = I('get.id',0,'intval');
        $result = $this->deal_model -> where(array("id"=>$id)) -> find();
        $this->assign("result", $result);
        $this->display();
    }
    public function editFileDisplay($type){
        $id = I('get.id',0,'intval');
        $result = $this->deal_model->where(array("id"=>$id))->find();
        $this->assign("result", $result);

        $results = $this->att_model->where(array("table_id"=>$id, "belong_to"=>$type))->select();
        $this->assign("results", $results);
        
        $this->display();
    }
    
    /**
     * 编辑保存
     **/
    public function editPost($url){
        if (IS_POST) {
			$this->dataCheck();
            $data = array_merge($_POST, $this->saveData(2));
            if ($this->deal_model->create()!==false) {
                $result=$this->deal_model->save($data);
                if ($result !== false) {
                    $this->success("保存成功！", $url);
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }
    public function editFilePost($url, $type){
        if (IS_POST) {
            $this->dataCheck();
            $data = array_merge($_POST, $this->saveData(2));
            if ($this->deal_model->create()!==false) {
                $result=$this->deal_model->save($data);
                if ($result !== false) {
                    $this->saveFile(I("post.id"), $type, 2);
                    $this->success("保存成功！", $url);
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }


	/**
	 * 重复验证
	 **/
	public function dataCheck(){
		if($this->check != NULL){
			$where = array();
			foreach($this->check as $key){
				$where[$key] = $_POST[$key];
            }
            if(array_key_exists("code",$where)){
                $where["code"] = "";
            }
            
			$where['id'] = array('neq', (I("request.id") != NULL ? I("request.id") : '0'));
            $where['is_deleted'] = array('eq',0);

			
			// 验证是否重复
			if($this->getCount($where) != '0'){
				$this->error(L("POST_CHECK"));
			}
		} else {
			return true;
		}
	}
    
    /**
     * 理论删除数据
     **/
    public function delete(){
        $id = I('get.id', 0, 'intval');
        if(!$id){
            $this->error("请选择要删除的数据！");
        }
        $data = array(
            'id'	=> $id,
            'is_deleted' => 1
        );
        if ($this->deal_model->save($data) !== false) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }
    
    /**
     * 修改状态为 发布
     */
    public function publish(){
		$param = $this->getParam();
		$url = U($param['m'].'/'.($param['fun'] != NULL ? $param['fun'] : 'index'));
        $id = I('get.id', 0, 'intval');
        if(!$id){
            $this->error("请选择要发布的数据！");
        }
        $data = array(
            'id'	=> $id,
            'is_publish' => 1
        );
        if ($this->deal_model->save($data) !== false) {
            $this->success("发布成功！", $url);
        } else {
            $this->error("发布失败！");
        }
    }
    
    /*
     * 上传文件
     */
     public function upload(){
        if(is_uploaded_file($_FILES['upFile']['tmp_name'])){
            // 验证图片宽高信息
            $uploadSize = getimagesize($_FILES['upFile']['tmp_name']);
            $upfile = $_FILES["upFile"]; 
            //获取数组里面的值 
            $name = $upfile["name"];//上传文件的文件名 
            $type = $upfile["type"];//上传文件的类型 
            $size = $upfile["size"];//上传文件的大小 
            $tmp_name = $upfile["tmp_name"];//上传文件的临时存放路径 
            
            // 上传结果
            $rtnType = "F";
            $destination = "";
            $error = $upFile["error"];//上传后系统返回的值 
            if($error == 0){
                
                // 获取文件后缀
                $pathinfo = pathinfo($name);
                
                $destination = "data/upload/".$_POST['folder']."/".date('Ymd'); 
                if (! file_exists ( $destination )) {
                    mkdir ( "$destination", 0777, true );
                }
                $destination .= "/".time().'.'.$pathinfo['extension'];
                // 如果有原始图片地址信息，删除图片
                if(file_exists($_POST['imageURL'])){
                    unlink($_POST['imageURL']);
                }
                // 如果有原始图片地址信息，删除图片
				if(file_exists($_POST['imageURL'])){
					unlink($_POST['imageURL']);
				}
				
                //把上传的临时文件移动到up目录下面 
                move_uploaded_file($tmp_name, $destination); 
                $rtnType = "T";
                $rtnMsg = "文件上传成功啦！";
            }elseif ($error == 1){ 
                $rtnMsg = "超过了文件大小，在php.ini文件中设置"; 
            }elseif ($error == 2){ 
                $rtnMsg = "超过了文件的大小MAX_FILE_SIZE选项指定的值"; 
            }elseif ($error == 3){ 
                $rtnMsg = "文件只有部分被上传"; 
            }elseif ($error == 4){ 
                $rtnMsg = "没有文件被上传"; 
            }else{ 
                $rtnMsg = "上传文件大小为0"; 
            } 
            
            // 输出结果
            exit(json_encode(array(
                'rtnType'	=> $rtnType,
                'rtnMsg'	=> $rtnMsg,
                'rtnResult'	=> $destination,
                'file_name'	=> $name,
                'file_size'	=> $size,
                'postfix'	=> $pathinfo['extension'],
                'file_type' => $type
            )));
            return $file_name = $name;
        } else {
            // 输出结果
            exit(json_encode(array(
                'rtnType'	=> "F",
                'rtnMsg'	=> "请选择上传文件"
            )));
        }
    }
    
    /*
     * 保存上传那文件信息进入文件表
     * $belong
     * 已完成：
     * 1. 监理规划
     * 2. 监理会议纪要
     * 3. 代建例会纪要
     * 4. 工程联系单
     * 5. 项目管理（代建）工作预告单
     * 6. 监理报告
     * 7. 通知公告
     * 8. 工程开工令
     * 9. 工程复工令
     * 10. 监理通知回复单
     * 12. 招标管理
     * 13. 旁站记录
     * 14. 服务款审批报审
     * 15. 工作联系单
     * 16. 现场签证
     * 17. 工作便函
     * 未完成：
     * 11. 监理实施细则
     **/
    public function saveFile($table_id, $belong, $type=1){
        if(IS_POST){
           /* if(!I("post.fileName") && $type == 1){
                $this->error("请选择需要上传的文件！");
            }*/
            for($i = 0; $i < count($_POST['fileName']); $i++){
                $files = array(
                    'file_name'	=> $_POST['fileName'][$i],
                    'file_path'	=> $_POST['filePath'][$i],
                    'belong_to'	=> $belong,
                    'table_id'	=> $table_id,
                    'file_type'	=> $_POST['postfix'][$i],
                    'file_size'	=> $_POST['file_size'][$i],
                );
                $this->att_model->add($files);
            }
        }
    }
    
    /**
     * 前台AjAX异步请求 删除文件
     **/
    public function delFile(){
        $id = I('post.id', 0, 'intval');
        if(!$id){
            exit(json_encode(array(
                'rtnType'	=> "F",
                'rtnMsg'	=> "请选择要删除的文件！"
            )));
        }
        $result = $this->att_model->delete($id);
        if($result !== false){
            exit(json_encode(array(
                'rtnType'	=> "T"
            )));
        } else {
            exit(json_encode(array(
                'rtnType'	=> "F",
                'rtnMsg'	=> "删除失败，请稍后重试！"
            )));
        }
    }
	
	/**
	 * 文件下载
	 * Class 'finfo' not found 解决方案
	 * 在 php.ini 中开启绑定的 php_fileinfo.dll
	 **/
	public function download(){
		// 调用类 
		$http = new \Org\Net\Http;
		$filename = I("get.filePath"); //"data/upload/news/20170411/1491900416.jpg";
		$showname = I("get.fileName"); //"Excel模板文件.jpg";
        print_r($showname);
        die();
		$http->download($filename, $showname);
	}
    
    /**
     * 保存日程详细信息
     **/
    public function saveLabourPlan($belong_to, $table_id){
        if($_POST['job_name'] != NULL){
            for($i = 0; $i < count($_POST['job_name']); $i++){
                $labour = array(
                    'belong_to'	=> $belong_to,
                    'table_id'	=> $table_id,
                    'plan_type'	=> $_POST['plan_type'][$i],
                    'job_name'	=> $_POST['job_name'][$i],
                    'this_week_count'	=> $_POST['this_week_count'][$i],
                    'next_week_count'	=> $_POST['next_week_count'][$i],
                );
                D("Common/LabourPlan")->add($labour);
            }
        }
    }
    
    /**
     * 删除原始数据
     **/
    public function deleteLabourPlan($belong_to, $table_id){
        D("Common/LabourPlan")->where(array("table_id"=>$table_id, "belong_to"=>$belong_to))->delete();
    }
	
	/**
	 * 获取符合条件的数据条数
	 **/
	public function getCount($where){
		return $this->deal_model->where($where)->count();
	}
	
	/**
	 * 获取当前路径参数
	 **/
	public function getParam(){
		$url = parse_url('http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]);
		$param = explode("&", $url['query']);
		foreach($param as $key){
			$data = explode("=", $key);
			$result[$data[0]] = $data[1];
		}
		return $result;
	}
	
	/**
	 * 获取部门信息
	 **/
	public function getDepartment(){
		return D("Common/Department")->field('id,department_name')->where(array('is_deleted' => array('neq', '1')))->select();
	}
	
	/**
	 * 获取登录人员部门级别信息
	 **/
	public function getDepartLevel(){
		if(session('deptid') == 0){
			$this->assign('level', 0);
		} else {
			$result = D("Common/Department")->field('department_role')->where(array('id' => session('deptid')))->find();
			$this->assign('level', $result['department_role']);
		}
	}
	
	/**
	 * 数字转换为中文
	 * @param  string|integer|float  $num  目标数字
	 * @param  integer $mode 模式[true:金额（默认）,false:普通数字表示]
	 * @param  boolean $sim 使用小写（默认）
	 * @return string
	 */
	/*
		//实例调用=====================================================
		$num = '0123648867.789';
		echo $num,'<br>';
		 //普通数字的汉字表示
		echo '普通:',number2chinese($num,false),'';
		echo '<br>';
		 //金额汉字表示
		echo '金额(简体):',number2chinese($num,true),'';
		echo '<br>';
		echo '金额(繁体):',number2chinese($num,true,false);
	*/
	function number2chinese($num,$mode = true,$sim = true){
		if(!is_numeric($num)) return '含有非数字非小数点字符！';
		$char    = $sim ? array('零','一','二','三','四','五','六','七','八','九')
		: array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖');
		$unit    = $sim ? array('','十','百','千','','万','亿','兆')
		: array('','拾','佰','仟','','萬','億','兆');
		$retval  = $mode ? '元':'点';
		//小数部分
		if(strpos($num, '.')){
			list($num,$dec) = explode('.', $num);
			$dec = strval(round($dec,2));
			if($mode){
				$retval .= "{$char[$dec['0']]}角{$char[$dec['1']]}分";
			}else{
				for($i = 0,$c = strlen($dec);$i < $c;$i++) {
					$retval .= $char[$dec[$i]];
				}
			}
		}
		//整数部分
		$str = $mode ? strrev(intval($num)) : strrev($num);
		for($i = 0,$c = strlen($str);$i < $c;$i++) {
			$out[$i] = $char[$str[$i]];
			if($mode){
				$out[$i] .= $str[$i] != '0'? $unit[$i%4] : '';
					if($i>1 and $str[$i]+$str[$i-1] == 0){
					$out[$i] = '';
				}
					if($i%4 == 0){
					$out[$i] .= $unit[4+floor($i/4)];
				}
			}
		}
		$retval = join('',array_reverse($out)) . $retval;
		return $retval;
	}










    /*********************    改变工程联系单的保存操作 -不清楚以上程序是否多处使用，没有大幅度编辑-  ******************************/

    //查看操作
    public function indexPageConstructionLaisonNoteFly($where){
        $eq = array(
            "eq" => "=",
            "neq" => "!=",
            "gt" => ">",
            "egt" => ">=",
            "lt" => "<",
            "elt" => "<=",
            "like" => "LIKE"
        );
        // 当前登录人
        $adminId = session('ADMIN_ID');
        $adminGroup = getUserInfo($adminId); 
        if($adminGroup[department_id] == ''){
            $adminGroup[department_id] = 0;
        }
        //发布人
        $condition = "d.is_deleted != 1 ";
        $condition .= " OR (1 = 0 ";
        //查看主送或抄送
        $condition .= "OR ('" . session("deptid") . "' IN 
        (SELECT department_id FROM hzzy_consignee WHERE table_id = d.id AND belong_to='gclxd'))) 
       ";
        //当前发布的所属部门等于当前用户的所属部门    或    假设发布人的权限为2级，当前用户是1级。  2 > 1 ： 所以当前用户有权限.
        // $condition .= " OR d.add_department= '$adminGroup[department_id]' OR 
        //              Com.department_role > '$adminGroup[department_role]' AND '$adminGroup[department_role]' in ('1','2','3') )";
        // $condition .= " AND (d.is_publish = '1' OR d.add_department = ".$adminGroup[department_id].")";
        // //权限设置 20171228
        $condition .= " AND (
            (d.is_publish = 0 AND (d.add_user = $adminId OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department) AND ((SELECT role_id FROM hzzy_users WHERE id=$adminId) IN('1','2','3'))))
            OR
            (d.is_publish = 1   
                AND (
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u1 LEFT JOIN hzzy_department d1 ON u1.department_id = d1.id WHERE u1.id=$adminId)
                        <= 
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u2 LEFT JOIN hzzy_department d2 ON u2.department_id = d2.id WHERE u2.id=d.add_user)
                )
                AND  '$adminGroup[department_role]' in ('1','2','3')
                OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department)
            )
            OR
            ((SELECT role_id FROM hzzy_users WHERE id=$adminId) = 0 AND d.is_publish = 1)
        )";
        foreach($where as $key => $v){
            if(count($v) > 1){
                $d = $eq[$v[0]] == NULL ? '=' : $eq[$v[0]];
                if($d != 'LIKE'){
                    $condition .= " AND $key $d '".$v[1]."'";
                } else {
                    $condition .= " AND $key $d '%".$v[1]."%'";
                }
            } else {
                $condition .= " AND $key = '$v'";
            }
        }
        $count=$this->deal_model->alias("d")
                    ->join(array(
                        ' LEFT JOIN '.C('DB_PREFIX').'users u ON d.add_user = u.id',
                        ' LEFT JOIN ' . C('DB_PREFIX') . 'department Com ON u.department_id = Com.id'
                    ))
                    ->where($condition)->count();
        $page = $this->page($count, 20);

        $results = $this->deal_model->alias("d")
            ->field('d.*,u.real_name')
            ->join(array(
                ' LEFT JOIN '.C('DB_PREFIX').'users u ON d.add_user = u.id',
                ' LEFT JOIN ' . C('DB_PREFIX') . 'department Com ON u.department_id = Com.id'
            ))
            ->where($condition)
            ->order("d.add_time DESC")
            ->limit($page->firstRow, $page->listRows)
            ->select();
        //exit($this->deal_model->getLastSql());
        $this->assign("page", $page->show('Admin'));
        $this->assign("results",$results);

        $this->display();
    }
    //添加保存
    public function addFilePostConstructionLaisonNoteFly($url, $type){
        if(IS_POST){
            $this->dataCheck();
            $data = array_merge($_POST, $this->saveData());
            if ($this->deal_model->create()!==false) {
                $result = $this->deal_model->add($data);
                if ($result!==false) {
                    //上传文件
                    $this->saveFile($result, $type);
                    //保存抄送
                    $cons = array(
                        "belong_to" => 'gclxd',
                        "table_id" => $result
                    );
                    foreach ($data['carbon_copy_department'] as $key => $vo) {
                        $cons['consignee_type'] = '2';
                        $cons['department_id'] = $vo;
                        $this->consignee_model->add($cons);
                    };
                    //返回成功
                    $this->success("添加成功！", $url);
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }
    //编辑保存
    public function editFilePostConstructionLaisonNoteFly($url, $type){
        if (IS_POST) {
            $this->dataCheck();
            $data = array_merge($_POST, $this->saveData(2));
            if ($this->deal_model->create()!==false) {
                $result=$this->deal_model->save($data);
                if ($result !== false) {
                    //上传文件
                    $this->saveFile(I("post.id"), $type, 2);
                    //修改保存抄送
                    $this->consignee_model->where(array('belong_to' => 'gclxd', 'table_id' => I("post.id", 0)))->delete();
                    $cons = array(
                        "belong_to" => 'gclxd',
                        "table_id" => I("post.id", 0)
                    );
                    foreach ($data['carbon_copy_department'] as $key => $vo) {
                        $cons['consignee_type'] = '2';
                        $cons['department_id'] = $vo;
                        $this->consignee_model->add($cons);
                    };

                    $this->success("保存成功！", $url);
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }












}